package com.gcph.zhuoba.player.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Handler;
import android.os.Message;

import com.gcph.zhuoba.main.bean.SocketData;
import com.gcph.zhuoba.main.common.Constant;
import com.gcph.zhuoba.util.L;
import com.google.gson.Gson;

/**
 * 预览客户端socket工具类
 * @author Administrator
 */
public class PlayerPreviewClient {
	
	//连接成功和失败
	public static final int CONNECTION_SUCC = 0;
	public static final int CONNECTION_FAIL = 1;
	
	//配对成功和失败
	public static final int PAIR_SUCC = 2;
	public static final int PAIR_FAIL = 3;
	
	
	// 客户端输入流
	private BufferedReader in;
	// 客户端输出流
	private PrintWriter out;
	
	private Socket socket;
	//单例对象
	private static PlayerPreviewClient instance;

	//得到新对象
	public static PlayerPreviewClient getInstance()
	{
		if(null == instance)
		{
			instance = new PlayerPreviewClient();
		}
		
		return instance;
	}
	/**
	 * 构造方法
	 */
	private PlayerPreviewClient() {}
	
	
	/**
	 * 建立连接
	 */
	public void setUpConnection(String serverIp, int serverPort,Handler handler) {
		Message msg = new Message();
		try {
			socket = new Socket(serverIp, serverPort);
			// 客户端输入流
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			// 客户端输出流
			out = new PrintWriter(socket.getOutputStream());
			
		} catch (UnknownHostException e) {
			msg.what=CONNECTION_SUCC;
			handler.sendMessage(msg);
			L.d("找不到相应的主机！");
		} catch (IOException e) {
			msg.what=CONNECTION_FAIL;
			handler.sendMessage(msg);
			L.d("建立连接失败");
		}
	}

	/**
	 * 处理接收数据
	 */
	public void handleReceive(Handler handler) {
		try {
			String line = null;
			Gson gson = new Gson();
			while (!(line=in.readLine()).equals("exit")) {
				Message msg = new Message();
				
				L.d("==收到line==="+line);
				SocketData socketData = gson.fromJson(line, SocketData.class);
				L.d("==收到socketData==="+socketData);
				if(null == socketData || null == socketData.getMethod())
				{
					continue;
				}
				//=========配对开始=========================
				if(socketData.getMethod().equals(Constant.SOCKET_METHOD_PAIR))
				{
					if("true".equals(socketData.getResult()))
					{
						msg.what=PAIR_SUCC;
						handler.sendMessage(msg);
						L.d("==配对成功===");
					}else
					{
						msg.what=PAIR_FAIL;
						handler.sendMessage(msg);
						continue;
					}
				}
			}
			L.d("=============socket结束  =============");
			in.close();
			out.close();
		} catch (IOException e) {
			Thread.currentThread().stop();
		}finally{
			Thread.currentThread().stop();
		}
	}

	/**
	 * 消息发送
	 * @param msg
	 */
	public void send(String msg){
		//如果不是调试模式
		if(!Constant.IS_DEBUG)
    	{
			L.d("sendSocketData==="+msg);
			synchronized (out) {
				out.println(msg);
				out.flush();
			}
    	}
	}
	
	/**
	 * 消息发送
	 * @param msg
	 */
	public void exit(){
		//如果不是调试模式
		if(!Constant.IS_DEBUG)
    	{
			L.d("====exit ====");
			synchronized (out) {
				out.println("{\"method\":\""+Constant.SOCKET_METHOD_EXIT+"\"}");
				out.flush();
				try {
					out.close();
					in.close();
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
    	}
	}
}